package logic

import (
	"context"
	"fmt"
	"vipshop/models/cache"
	"vipshop/models/mysql"

	"vipshop/vipshoprpc/internal/svc"
	"vipshop/vipshoprpc/vipshoprpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ForgetLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewForgetLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ForgetLogic {
	return &ForgetLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ForgetLogic) Forget(in *vipshoprpc.ForgetRequest) (*vipshoprpc.ForgetResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User
	mysql.DB.Debug().Where("account=?", in.Account).Find(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("账号不存在，无法修改")
	}
	if user.Password == in.Password {
		return nil, fmt.Errorf("新密码和原密码一致，无法修改")
	}
	if in.Password != in.Newpassword {
		return nil, fmt.Errorf("两次密码输入不一致，无法修改")
	}
	res1, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Account).Result()
	if in.SendSmsCode != res1 {
		return nil, fmt.Errorf("短信验证码错误")
	}
	res2, _ := cache.Rdb.Get(l.ctx, "captcha"+in.Account).Result()
	if in.CaptchaImage != res2 {
		return nil, fmt.Errorf("图片验证码错误")
	}
	users := mysql.User{
		Password: in.Newpassword,
	}
	mysql.DB.Debug().Updates(&users)

	return &vipshoprpc.ForgetResponse{
		UserId: int64(users.ID),
	}, nil
}
